﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static System.Net.Mime.MediaTypeNames;
using System.Net;
using AuSys.Models.Identities;
using AuSys.Services.App.UserInfo.Abstractions;

namespace AuSys.Services.App.ActionFilters
{
    public class UserTypeRestrictedFilter(
        IUserInfoService userInfoService
        ) : IAsyncResourceFilter
    {
        public UserType Level { get; set; }

        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            var type = userInfoService.GetUserInfo().Type;
            if (type < Level)
            {
                context.Result = new ContentResult()
                {
                    Content = "权限等级不足",
                    ContentType = Text.Plain,
                    StatusCode = (int)HttpStatusCode.Forbidden
                };
            }
            else
                await next();
        }
    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class UserTypeRestrictedAttribute(
        UserType level = UserType.Member)
        : Attribute, IFilterFactory
    {
        public bool IsReusable => false;
        public UserType Level { get; set; } = level;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            var f = serviceProvider.GetRequiredService<UserTypeRestrictedFilter>();
            f.Level = Level;
            return f;
        }
    }
}
